package com.songhq.data.log.util;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class LogUtil
{
  private static Logger log_call_err = MLogFactory.getLog("LOG_CALL_ERR");
  private static Logger log_comm = MLogFactory.getLog("LOG_COMM");
  private static Logger log_cache_update = MLogFactory.getLog("LOG_CACHE_UPDATE");

  private static String LOCAL_IP = getLocalIp();

  public static String getIp()
  {
    return LOCAL_IP;
  }

  private static String getLocalIp()
  {
    try
    {
      Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
      InetAddress ip = null;
      while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement();

        Enumeration addresses = netInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
          ip = (InetAddress)addresses.nextElement();
          if ((ip != null) && ((ip instanceof Inet4Address))) {
            String str = ip.getHostAddress();
            if (!str.startsWith("10.151"))
              return str;
          }
        }
      }
    }
    catch (SocketException e) {
      e.printStackTrace();
    }
    return "";
  }

  public static String commonHeaders(String methodName, long useTime)
  {
    String logContent = "";
    String serverIp = getIp();
    if (null != RequestContextHolder.getRequestAttributes()) {
      HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
      String mobile = getString(request.getHeader("mobile"));
      String userId = getString(request.getHeader("userId"));
      String clientId = getString(request.getHeader("clientId"));

      String url = request.getRequestURL().toString();
      logContent = String.format("%s|%s|%s|%s|%s|%s|%s|%s", new Object[] { mobile, userId, clientId, url, methodName, Long.valueOf(useTime), serverIp, getBussId() });
    } else {
      logContent = String.format("%s|%s|%s|%s|%s|%s|%s|%s", new Object[] { "", "", "", "", methodName, Long.valueOf(useTime), serverIp, getBussId() });
    }
    return logContent;
  }

  public static String feignComm(String methodName, int status, long useTime)
  {
    String logContent = String.format("%s|%s|%s|%s|%s", new Object[] { getIp(), methodName, Integer.valueOf(status), Long.valueOf(useTime), getBussId() });
    return logContent;
  }

  public static String getString(String str) {
    return str == null ? "" : str;
  }

  public static Method getMethod(JoinPoint joinPoint) throws Exception {
    Object target = joinPoint.getTarget();
    String methodName = joinPoint.getSignature().getName();
    Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
    Method method = target.getClass().getMethod(methodName, parameterTypes);
    return method;
  }

  public static String getBussId() {
    String bussId = "";
    //这里使用sleuth找不到
//    try {
//    	DefaultTracer tracer = (DefaultTracer)ApplicationContextRegister.getBean(DefaultTracer.class);
//      if ((null != tracer) && 
//        (null != tracer.getCurrentSpan()))
//        bussId = tracer.getCurrentSpan().getBaggageItem("bussId");
//    }
//    catch (Exception e)
//    {
//      return "";
//    }
    return bussId;
  }

  public static void info(String message) {
    String logString = null;
    String logContent = null;
    String serverIp = getIp();
    if (null != RequestContextHolder.getRequestAttributes()) {
      HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
      String mobile = getString(request.getHeader("mobile"));
      String userId = getString(request.getHeader("userId"));
      String clientId = getString(request.getHeader("clientId"));
      String bussId = getBussId();

      String url = request.getRequestURL().toString();
      logContent = String.format("%s|%s|%s|%s|%s|%s", new Object[] { mobile, userId, clientId, url, serverIp, bussId });
    } else {
      logContent = String.format("%s|%s|%s|%s|%s|%s", new Object[] { "", "", "", "", serverIp, getBussId() });
    }
    logString = String.format("%s|^%s", new Object[] { logContent, message });
    log_comm.info(logString);
  }

  public static void error(String message, Throwable ex, String method)
  {
    String logString = String.format("%s|%s|^%s^%s", new Object[] { method, getBussId(), message, ExceptionUtil.getMessage(ex) });
    log_call_err.error(logString);
  }

  public static void error(Throwable ex, String method) {
    String logString = String.format("%s|%s|^%s", new Object[] { method, getBussId(), ExceptionUtil.getMessage(ex) });
    log_call_err.error(logString);
  }

  public static void debug(String method, String message) {
    String logString = String.format("%s|%s|^%s", new Object[] { method, getBussId(), message });
    log_comm.debug(logString);
  }

  public static void error(String message, Exception e, String method) {
    String logString = String.format("%s|%s|^%s^%s", new Object[] { method, getBussId(), message, ExceptionUtil.getMessage(e) });
    log_call_err.error(logString);
  }

  public static void error(Exception e, String method) {
    String logString = String.format("%s|%s|^%s", new Object[] { method, getBussId(), ExceptionUtil.getMessage(e) });
    log_call_err.error(logString);
  }

  public static void error(String message, String method) {
    String logString = String.format("%s|%s|^%s", new Object[] { method, getBussId(), message });
    log_call_err.error(logString);
  }

  public static void logCacheUpdate(String uId, String topic, String cacheType, String processType, int processResult, long useTime, String value, String logMsg) {
    int endIndex = 200;
    int bodyLen = value.length();
    if (bodyLen < endIndex) {
      endIndex = bodyLen;
    }
    String subValue = value.substring(0, endIndex);
    String logString = String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|^%s", new Object[] { uId, topic, cacheType, processType, Integer.valueOf(processResult), Long.valueOf(useTime), getIp(), subValue, getBussId(), logMsg });
    log_cache_update.info(logString);
  }
}